using DeviceCommons.DataHandling;
using DeviceCommons.DeviceMessages.Abstractions;
using DeviceCommons.DeviceMessages.Builders;
using DeviceCommons.DeviceMessages.Models.V1;
using DeviceCommons.DeviceMessages.Serialization;
using DeviceCommons.Exceptions;
using DeviceCommons.Validation;
using System.Buffers;

namespace DeviceCommons.DeviceMessages.Factories
{
    /// <summary>
    /// 设备消息处理器
    /// 提供简化的API接口，降低使用复杂度
    /// </summary>
    public class DeviceMessageProcessor
    {
        private readonly IDeviceMessageParser _parser;
        private readonly IDeviceMessageSerializer _serializer;

        public DeviceMessageProcessor()
        {
            _parser = DeviceMessageSerializerProvider.MessagePar;
            _serializer = DeviceMessageSerializerProvider.MessageSer;
        }

        /// <summary>
        /// 注册设备类型配置
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <param name="configuration">配置构建器</param>
        /// <returns>处理器实例（支持链式调用）</returns>
        public DeviceMessageProcessor RegisterDeviceType(byte deviceType, Action<DeviceStateConfigurationBuilder> configuration)
        {
            try
            {
                DeviceStateConfigurationRegistry.RegisterConfiguration(deviceType, configuration);
                return this;
            }
            catch (Exception ex)
            {
                throw new DeviceMessageValidationException(
                    ValidationErrorType.InvalidConfiguration,
                    $"注册设备类型 {deviceType} 失败: {ex.Message}",
                    nameof(deviceType),
                    "有效的设备类型配置",
                    ex.Message);
            }
        }

        /// <summary>
        /// 解析设备消息
        /// </summary>
        /// <param name="hexString">十六进制字符串</param>
        /// <param name="enableFastParsing">是否启用快速解析</param>
        /// <returns>解析后的设备消息</returns>
        public IDeviceMessage ParseMessage(string hexString, bool enableFastParsing = true)
        {
            try
            {
                // 验证输入
                if (string.IsNullOrEmpty(hexString))
                {
                    throw new DeviceMessageValidationException(
                        ValidationErrorType.InvalidInput,
                        "消息字符串不能为空",
                        nameof(hexString),
                        "有效的十六进制字符串",
                        "null 或空字符串");
                }

                // 转换十六进制字符串
                var bytes = ConvertHexStringToBytes(hexString);
                
                // 设置解析上下文
                var context = ParsingContext.Create();
                context.EnableFastParsing = enableFastParsing;
                
                if (_parser is IContextAwareParser contextAwareParser)
                {
                    contextAwareParser.SetContext(context);
                }

                // 解析消息
                return _parser.Parser(bytes);
            }
            catch (DeviceMessageValidationException)
            {
                throw; // 重新抛出验证异常
            }
            catch (Exception ex)
            {
                throw new DeviceMessageValidationException(
                    ValidationErrorType.ParsingFailed,
                    $"消息解析失败: {ex.Message}",
                    nameof(hexString),
                    "有效的设备消息格式",
                    ex.Message);
            }
        }

        /// <summary>
        /// 序列化设备消息
        /// </summary>
        /// <param name="message">设备消息</param>
        /// <returns>十六进制字符串</returns>
        public string SerializeMessage(IDeviceMessage message)
        {
            try
            {
                // 验证输入
                if (message == null)
                {
                    throw new DeviceMessageValidationException(
                        ValidationErrorType.InvalidInput,
                        "设备消息不能为空",
                        nameof(message),
                        "有效的设备消息对象",
                        "null");
                }

                // 序列化消息
                var buffer = new ArrayBufferWriter<byte>();
                var hexString = _serializer.Serializer(buffer, message, isEncrypt: false, isCompress: false);
                return hexString;
            }
            catch (DeviceMessageValidationException)
            {
                throw; // 重新抛出验证异常
            }
            catch (Exception ex)
            {
                throw new DeviceMessageValidationException(
                    ValidationErrorType.SerializationFailed,
                    $"消息序列化失败: {ex.Message}",
                    nameof(message),
                    "有效的设备消息对象",
                    ex.Message);
            }
        }

        /// <summary>
        /// 创建设备消息构建器
        /// </summary>
        /// <returns>设备消息构建器</returns>
        public IDeviceMessageBuilder CreateMessage()
        {
            return DeviceMessageBuilder.Create();
        }

        /// <summary>
        /// 获取注册的设备类型统计
        /// </summary>
        /// <returns>统计信息</returns>
        public (int TotalDeviceTypes, int TotalStates) GetStatistics()
        {
            return DeviceStateConfigurationRegistry.GetStatistics();
        }

        /// <summary>
        /// 检查设备类型是否已注册
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>是否已注册</returns>
        public bool IsDeviceTypeRegistered(byte deviceType)
        {
            return DeviceStateConfigurationRegistry.IsRegistered(deviceType);
        }

        /// <summary>
        /// 获取设备类型配置
        /// </summary>
        /// <param name="deviceType">设备类型</param>
        /// <returns>设备配置</returns>
        public IDeviceStateConfiguration? GetDeviceConfiguration(byte deviceType)
        {
            return DeviceStateConfigurationRegistry.GetConfiguration(deviceType);
        }

        /// <summary>
        /// 验证设备消息格式
        /// </summary>
        /// <param name="hexString">十六进制字符串</param>
        /// <returns>验证结果</returns>
        public (bool IsValid, string? ErrorMessage) ValidateMessageFormat(string hexString)
        {
            try
            {
                if (string.IsNullOrEmpty(hexString))
                {
                    return (false, "消息字符串不能为空");
                }

                var bytes = ConvertHexStringToBytes(hexString);
                DeviceMessageValidator.ValidateMessageData(bytes, nameof(hexString));
                return (true, null);
            }
            catch (Exception ex)
            {
                return (false, ex.Message);
            }
        }

        /// <summary>
        /// 转换十六进制字符串为字节数组
        /// </summary>
        /// <param name="hexString">十六进制字符串</param>
        /// <returns>字节数组</returns>
        private static byte[] ConvertHexStringToBytes(string hexString)
        {
            // 移除空格和前缀
            hexString = hexString.Replace(" ", "").Replace("0x", "").Replace("0X", "");
            
            // 处理 dec,raw| 前缀
            if (hexString.StartsWith("dec,raw|"))
            {
                hexString = hexString.Substring("dec,raw|".Length);
            }
            
            if (hexString.Length % 2 != 0)
            {
                throw new ArgumentException("十六进制字符串长度必须为偶数");
            }

            var bytes = new byte[hexString.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
            }
            return bytes;
        }

        /// <summary>
        /// 转换字节数组为十六进制字符串
        /// </summary>
        /// <param name="bytes">字节数组</param>
        /// <returns>十六进制字符串</returns>
        private static string ConvertBytesToHexString(ReadOnlySpan<byte> bytes)
        {
            return BitConverter.ToString(bytes.ToArray()).Replace("-", "");
        }
    }
}
